import SMErouter from 'sme-router'
import index from 'v/index'
import login from 'v/login'
import adminList from 'v/adminList'
import advList from 'v/advList'
import { getAdminList } from './api/reqAdmin'
import { reqLogin, reqLogout } from './api/reqLogin'
import { verifyToken } from './api/verifyToken'
import { addAdv, getAdvs, deleteAdv, getAdvOne, updateAdv } from './api/reqAdv'
import { formatDate } from './utils/format'

import './css/index.css'

const router = new SMErouter('root', 'html5')
window.router = router

router.route('/index', async (req, res, next) => {
  const result = await verifyToken()
  console.log(result, req)
  if (!result.success) {
    toastr.error('登录失效请重新登录')
    res.redirect('/login')
    return
  }
  next(
    index({
      url: req.url,
      subRoute: res.subRoute(),
      body: req.body,
    })
  )

  $('#logoutBtn').on('click', async () => {
    // 给服务器发送请求,删除数据库中存储的token
    await reqLogout(req.body._id)
    // 删除本地缓存中的token
    localStorage.clear()
    toastr.success('已退出登录')
    res.redirect('/login')
  })
})
router.route('/login', (req, res) => {
  res.render(login())
  // login页面表单校验
  $('#loginBtn').on('click', async function (e) {
    e.preventDefault()
    const user = $('#user').val().trim()
    const pass = $('#pass').val().trim()
    if (/^[a-z]{2,6}$/.test(user) && /^\d{6,8}$/.test(pass)) {
      const result = await reqLogin({ username: user, password: pass })
      if (result.success) {
        localStorage.setItem('token', result.token)
        router.go('/index', result.admin)
      } else {
        toastr.error('登录失败')
      }
    } else {
      toastr.error('请按照要求填写表单')
    }
  })
})

router.route('/index/adminList', async (req, res) => {
  const result = await verifyToken()
  if (!result.success) {
    res.redirect('/login')
    return
  }
  try {
    const result = await getAdminList()
    result.success
      ? res.render(adminList(formatDate(result.data)))
      : toastr.error('网络错误,请稍后再试')
  } catch (error) {
    toastr.error('网络错误,请稍后再试')
  }
})

router.route('/index/advList', async (req, res) => {
  let result = await verifyToken()
  if (!result.success) {
    res.redirect('/login')
    return
  }
  result = await getAdvs()
  res.render(advList(result.data))

  $('#index-content').on('click', '#addBtn', () => {
    $('.modal .modal-title').text('添加广告')
    $('#uploadAdvForm')[0].reset()
    $('#showImg')[0].style.display = 'none'
  })

  $('#index-content').on('click', '#addAdvBtn', async (e) => {
    const formdata = new FormData($('#uploadAdvForm')[0])
    let result = null
    if ($('#addAdvBtn').text().trim() === '保存') {
      result = await addAdv(formdata)
    } else if ($('#addAdvBtn').text().trim() === '修改') {
      formdata.append('id', localStorage.getItem('id'))
      result = await updateAdv(formdata)
    }
    result.success ? toastr.success(result.msg) : toastr.error(result.msg)
    res.render(advList(result.data))
  })

  $('#index-content').on(
    'change',
    '#uploadAdvForm input[type=file]',
    async (e) => {
      const preImg = $('#showImg')[0]
      // 1- 生成FileReader实例
      const reader = new FileReader()
      try {
        // 2- 生成图片base64数据
        reader.readAsDataURL(e.target.files[0])
        // 3- 通过load事件得到结果
        reader.onload = function (e) {
          preImg.style.display = 'block'
          preImg.src = e.target.result
        }
      } catch (error) {
        preImg.style.display = 'none'
      }
    }
  )

  $('#index-content').on(
    'click',
    '#advListWrap button.btn-danger',
    async (e) => {
      const id = e.target.dataset.id
      // console.log(id)
      const result = await deleteAdv(id)
      result.success ? toastr.success(result.msg) : toastr.error(result.msg)
      res.render(advList(result.data))
    }
  )

  $('#index-content').on('click', '.updateAdvBtn', async (e) => {
    const id = e.target.dataset.id
    localStorage.setItem('id', id)

    const result = await getAdvOne(id)
    $('.modal .modal-title').text('修改广告')
    $('#uploadAdvForm input[name="advTitle"]').val(result.data.advTitle)
    $('#uploadAdvForm input[name="advCategory"]').val(result.data.advCategory)
    $('#uploadAdvForm input[name="advLink"]').val(result.data.advLink)
    $('#showImg')[0].src = result.data.advAvatar
    $('#showImg')[0].style.display = 'block'
    $('#addAdvBtn').text('修改')
  })
})

router.route('*', (req, res) => {
  res.redirect('/login')
})
